package com.bw.lib_mvicore.ui

import android.os.Bundle
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast



abstract class BaseLazyLoadFragment : Fragment() {
    /**
     * 实体是否初始化
     */
    protected var isInit:Boolean=false

    /**
     * 是否已经完成加载
     */
    protected var isLoaded:Boolean=false

    protected lateinit var mView:View

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        mView = getFragmentRootView(inflater,container,savedInstanceState)
        isInit = true
        prepareLoadData()

        return mView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initEvent()
    }
    /**
     * 初始化事件
     */
    abstract fun initEvent();


    private fun prepareLoadData() {
        if (!isInit)return

        if (userVisibleHint){
            lazyLoad()
            isLoaded=true
        }else{
            if (isLoaded){
                stopLoad()
            }
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        prepareLoadData()
    }

    open fun stopLoad(){}

    abstract fun lazyLoad()

    /**
     * 获取Fragment视图
     */
    abstract fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View


    override fun onDestroyView() {
        super.onDestroyView()
        isInit = false
        isLoaded = false
    }

    /**
     * 显示提示消息
     */
    protected fun showMsg(msg: String?){

        if (activity is BaseActivity){
            (activity as BaseActivity).showMsg(msg?:"")
        }

    }

    /**
     * 获取框架中BaseActivity 注意可能为空 取决于Activity是否继承BaseActivity
     */
    protected fun getBaseActivity():BaseActivity{
        return requireActivity() as BaseActivity
    }


}